import { Injectable, UnauthorizedException } from "@nestjs/common";
import { UsersService } from "../users/users.service";
import * as bcrypt from "bcryptjs";
import * as jwt from "jsonwebtoken";
import * as dotenv from "dotenv";
dotenv.config();
@Injectable()
export class AuthService {
  constructor(private users: UsersService) {}
  async register(username: string, password: string) {
    const exist = await this.users.findByUsername(username);
    if (exist) throw new UnauthorizedException("User exists");
    const passwordHash = await bcrypt.hash(password, 10);
    const user = await this.users.create({ username, passwordHash });
    return this.login(user);
  }
  async validateUser(username: string, password: string) {
    const user = await this.users.findByUsername(username);
    if (!user) return null;
    const ok = await bcrypt.compare(password, user.passwordHash);
    return ok ? user : null;
  }
  async login(user: any) {
    const token = jwt.sign(
      { sub: user.id, username: user.username },
      process.env.JWT_SECRET || "secret",
      { expiresIn: "7d" }
    );
    return { access_token: token };
  }
}
